import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { FileReference, DiffResult, DiffViewState } from '../types/basic'
import { useHistoryStore } from './history'

export const useDiffStore = defineStore('diff', () => {
  // State
  const leftFile = ref<FileReference | null>(null)
  const rightFile = ref<FileReference | null>(null)
  const diffResult = ref<DiffResult | null>(null)
  const viewMode = ref<'side-by-side' | 'inline'>('side-by-side')
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const state = computed<DiffViewState>(() => ({
    leftFile: leftFile.value,
    rightFile: rightFile.value,
    diffResult: diffResult.value,
    viewMode: viewMode.value
  }))

  const hasFiles = computed(() => leftFile.value !== null && rightFile.value !== null)
  const hasDiff = computed(() => diffResult.value !== null)
  const isComparable = computed(() => {
    if (!leftFile.value || !rightFile.value) return false
    return leftFile.value.path === rightFile.value.path
  })

  const diffStats = computed(() => {
    if (!diffResult.value) return null
    return {
      additions: diffResult.value.additions,
      deletions: diffResult.value.deletions,
      modifications: diffResult.value.modifications,
      total: diffResult.value.additions + diffResult.value.deletions + diffResult.value.modifications
    }
  })

  // Actions
  const setLeftFile = async (versionId: string, fileId: string, path: string) => {
    try {
      isLoading.value = true
      error.value = null
      
      const historyStore = useHistoryStore()
      const content = await historyStore.getFileContent(versionId, fileId)
      
      leftFile.value = {
        versionId,
        fileId,
        path,
        content,
        timestamp: Date.now() // This should come from the actual file timestamp
      }

      // Auto-compare if both files are set
      if (rightFile.value && isComparable.value) {
        await compareDiff()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载文件失败'
    } finally {
      isLoading.value = false
    }
  }

  const setRightFile = async (versionId: string, fileId: string, path: string) => {
    try {
      isLoading.value = true
      error.value = null
      
      const historyStore = useHistoryStore()
      const content = await historyStore.getFileContent(versionId, fileId)
      
      rightFile.value = {
        versionId,
        fileId,
        path,
        content,
        timestamp: Date.now() // This should come from the actual file timestamp
      }

      // Auto-compare if both files are set
      if (leftFile.value && isComparable.value) {
        await compareDiff()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载文件失败'
    } finally {
      isLoading.value = false
    }
  }

  const setViewMode = (mode: 'side-by-side' | 'inline') => {
    viewMode.value = mode
  }

  const compareDiff = async () => {
    if (!leftFile.value || !rightFile.value) {
      error.value = '请选择两个文件进行对比'
      return
    }

    if (!isComparable.value) {
      error.value = '只能对比同一文件的不同版本'
      return
    }

    try {
      isLoading.value = true
      error.value = null

      // Simple diff calculation (in a real implementation, you'd use a proper diff library)
      const leftLines = leftFile.value.content.split('\n')
      const rightLines = rightFile.value.content.split('\n')
      
      let additions = 0
      let deletions = 0
      let modifications = 0

      // Basic diff logic - this is simplified
      const maxLines = Math.max(leftLines.length, rightLines.length)
      for (let i = 0; i < maxLines; i++) {
        const leftLine = leftLines[i]
        const rightLine = rightLines[i]
        
        if (leftLine === undefined && rightLine !== undefined) {
          additions++
        } else if (leftLine !== undefined && rightLine === undefined) {
          deletions++
        } else if (leftLine !== rightLine) {
          modifications++
        }
      }

      diffResult.value = {
        additions,
        deletions,
        modifications,
        chunks: [] // This would be populated by a proper diff algorithm
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '对比失败'
    } finally {
      isLoading.value = false
    }
  }

  const clearDiff = () => {
    leftFile.value = null
    rightFile.value = null
    diffResult.value = null
    error.value = null
  }

  const swapFiles = () => {
    const temp = leftFile.value
    leftFile.value = rightFile.value
    rightFile.value = temp
    
    if (hasFiles.value && isComparable.value) {
      compareDiff()
    }
  }

  return {
    // State
    leftFile,
    rightFile,
    diffResult,
    viewMode,
    isLoading,
    error,
    
    // Getters
    state,
    hasFiles,
    hasDiff,
    isComparable,
    diffStats,
    
    // Actions
    setLeftFile,
    setRightFile,
    setViewMode,
    compareDiff,
    clearDiff,
    swapFiles
  }
})